﻿using Emgu.CV.Structure;
using Emgu.CV;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NetworkOPSUI
{
    public partial class UserControl_IPCshow : UserControl
    {
        private VideoCapture _capture;
        private string _rtspUrl;
        public UserControl_IPCshow()
        {
            InitializeComponent();
            pictureBox_IPC.SizeMode = PictureBoxSizeMode.StretchImage;
        }

        public string CameraName
        {
            get { return textBox_ipcName.Text; }
            set { textBox_ipcName.Text = value; }
        }

        public string CameraIP
        {
            get { return textBox_IpcIP.Text; }
            set { textBox_IpcIP.Text = value; }
        }

        public string RtspUrl
        {
            get { return _rtspUrl; }
            set
            {
                _rtspUrl = value;
                StartCapture();
            }
        }

        private void StartCapture()
        {
            if (_capture != null)
            {
                _capture.Stop();
                _capture.Dispose();
            }

            _capture = new VideoCapture(_rtspUrl);
            _capture.ImageGrabbed += Capture_ImageGrabbed;
            _capture.Start();
        }

        private void Capture_ImageGrabbed(object sender, EventArgs e)
        {
            Mat frame = new Mat();
            _capture.Retrieve(frame);
            if (!frame.IsEmpty)
            {
                pictureBox_IPC.Image = frame.ToImage<Bgr, byte>().ToBitmap();
                _capture.Stop(); 
                _capture.Dispose();
            }
        }

        private void pictureBox_IPC_Click(object sender, EventArgs e)
        {

        }

        //protected override void Dispose(bool disposing)
        //{
        //    if (disposing)
        //    {
        //        if (_capture != null)
        //        {
        //            _capture.Stop();
        //            _capture.Dispose();
        //        }
        //        if (components != null)
        //        {
        //            components.Dispose();
        //        }
        //    }
        //    base.Dispose(disposing);
        //}

    }
}
